﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Linq;

namespace Common
{
    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class Appsettings
    {
        static IConfiguration _Configuration { get; set; }

        static string _contentPath { get; set; }

        public Appsettings(IConfiguration configuration)
        {
            _Configuration = configuration;
        }
        public Appsettings(string contentpath)
        {
            string path = "appsettings.json";

            //如果你把配置文件是根据环境变量来分开的，可以这样写
            //path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
            _Configuration = new ConfigurationBuilder()
              .SetBasePath(contentpath)
              .Add(new JsonConfigurationSource { Path = path, Optional = false, ReloadOnChange = true })//这样的话，可以直接读目录里的json文件，而不是 bin 文件夹下的，所以不用修改复制属性
              .Build();
        }

        public static string app(params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    return _Configuration[string.Join(":", sections)];
                }
            }
            catch(Exception ex) { }
            return "";
        }
    }
}
